package com.jy.appmarket.activity;

import java.util.ArrayList;
import java.util.List;

import com.jy.app.market.idata.card.Card;
import com.jy.app.market.idata.card.CardApk;
import com.jy.app.market.idata.card.CardApkTop;
import com.jy.app.market.idata.data.Apk;
import com.jy.app.market.idata.data.PageCard;
import com.jy.appmarket.R;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.newnetwork.RequestQueue;
import com.jy.appmarket.newnetwork.Response.ErrorListener;
import com.jy.appmarket.newnetwork.Response.Listener;
import com.jy.appmarket.newnetwork.VolleyError;
import com.jy.appmarket.newnetwork.api.ApiRequest;
import com.jy.appmarket.newnetwork.api.ApiResult;
import com.jy.appmarket.newnetwork.api.MarketApi;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.FastBlur;
import com.jy.appmarket.utils.IdataUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.view.LoadingView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class GameBoxActivity extends FragmentActivity
		implements Listener<ApiResult>, ErrorListener, LoadingView.OnClickListener, OnItemClickListener {

	private static final String TAG = GameBoxActivity.class.getSimpleName();
	private RequestQueue mQueue;

	private GridView mGridview;
	private GameBoxAdapter mAdapter;

	private List<Apk> mApks = new ArrayList<Apk>();
	private static final String API = "gamebox";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_gamebox);
		mGridview = findViewById(R.id.gridview);

		mAdapter = new GameBoxAdapter(mApks);
		mGridview.setAdapter(mAdapter);
		mGridview.setOnItemClickListener(this);

		Bitmap blur = getBluredBackground();
		ImageView background = findViewById(R.id.gamebox_background);
		if (blur != null) {
			background.setImageBitmap(blur);
		} else {
			background.setVisibility(View.GONE);
		}

		mQueue = MarketApi.newApiRequestQueue(this);
		ApiRequest request = ApiRequest.get(API, this, this);
		mQueue.add(request);
		showLoading();
	}

	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mQueue.stop();
	}

	private void showContent() {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.content_view);
		loadingview.setVisibility(View.GONE);
		contentview.setVisibility(View.VISIBLE);

	}

	private void showLoading() {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.content_view);

		loadingview.setVisibility(View.VISIBLE);
		loadingview.setTextColor(Color.WHITE);
		loadingview.showWaitView(getString(R.string.ptr1_loading_wait));
		loadingview.setImage(0);
		contentview.setVisibility(View.GONE);
	}

	private void showError(LoadingView.OnClickListener l) {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.content_view);

		loadingview.setVisibility(View.VISIBLE);
		loadingview.setTextColor(Color.WHITE);
		loadingview.setOnClickListener(l);
		loadingview.showErrorView("连接失败，请点击此处重试");
		loadingview.setImage(0);
		contentview.setVisibility(View.GONE);
	}

	private void showEmpty(String text) {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.content_view);

		loadingview.setVisibility(View.VISIBLE);
		loadingview.setTextColor(Color.WHITE);
		loadingview.showEmptyView(text);
		loadingview.setImage(0);
		contentview.setVisibility(View.GONE);
	}

	private Bitmap getBluredBackground() {
		try {
			WallpaperManager wm = WallpaperManager.getInstance(this);
			BitmapDrawable d = (BitmapDrawable) wm.getDrawable();
			return FastBlur.blurBitmap(d.getBitmap());
		} catch (Exception e) {
			LogUtil.d(TAG, "failed to blur background:" + (e == null ? "" : e.getMessage()));
		}
		return null;
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		LogUtil.d(TAG, "onErrorResponse:" + error);
		showError(this);
	}

	@Override
	public void onResponse(ApiResult response) {
		LogUtil.d(TAG, "onResponse:" + response);
		if (!response.isOK()) {
			showError(this);
			return;
		}
		PageCard page = response.getData(PageCard.class);
		if (page == null) {
			showError(this);
			return;
		}
		mApks.clear();
		List<Card> cards = page.getCards();
		if (cards == null || cards.isEmpty()) {
			showEmpty("这里空空如也");
			return;
		}
		for (Card card : cards) {
			Apk apk = null;
			if (card instanceof CardApkTop) {
				apk = ((CardApkTop) card).getApk();
			} else if (card instanceof CardApk) {
				apk = ((CardApk) card).getApk();
			}
			if (apk == null) {
				continue;
			}
			String pkg = apk.getPackageName();
			if (PackageUtils.isPackageInstalled(this, pkg)) {
				continue;
			}
			if (DownloadUtils.downloadExist(this, pkg)) {
				continue;
			}
			mApks.add(apk);
		}

		if (mApks.isEmpty()) {
			showEmpty("这里空空如也");
		} else {
			showContent();
		}
	}

	@Override
	public void onLoadingViewClick(View view) {
		showLoading();
		ApiRequest request = ApiRequest.get(API, this, this);
		mQueue.add(request);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position >= mApks.size()) {
			return;
		}

		String source = new ApkSource("gamebox", position, null).toSourceString();

		final Apk apk = mApks.get(position);
		Intent intent = new Intent(this, AppDetailActivity.class);
		intent.putExtra(AppDetailActivity.EXTRA_NAME, apk.getTitle());
		intent.putExtra(AppDetailActivity.EXTRA_PKG, apk.getPackageName());
		intent.putExtra(AppDetailActivity.EXTRA_SOURCE, source);
		startActivity(intent);
	}

	private static final class GameBoxAdapter extends BaseAdapter {
		private final List<Apk> mApks;
		private final ImageLoader loader;
		private final DisplayImageOptions options;

		public GameBoxAdapter(List<Apk> apks) {
			this.mApks = apks;
			loader = ImageLoader.getInstance();
			options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
					.resetViewBeforeLoading(false).showImageOnLoading(R.drawable.default_loading_icon).build();
		}

		@Override
		public int getCount() {
			if (mApks == null) {
				return 0;
			} else {
				return Math.min(mApks.size(), 6);
			}
		}

		@Override
		public Object getItem(int position) {
			return mApks.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = View.inflate(parent.getContext(), R.layout.gamebox_list_item, null);
				holder = new ViewHolder();
				holder.icon = convertView.findViewById(R.id.icon);
				holder.title = convertView.findViewById(R.id.title);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final Apk apk = mApks.get(position);
			loader.displayImage(IdataUtils.getIconUrl(apk.getIcons()), holder.icon, options);
			holder.title.setText(apk.getTitle());

			return convertView;
		}

	}

	private static class ViewHolder {
		public ImageView icon;
		public TextView title;
	}
}